﻿/*********************************************************

    Copyright (c) Microsoft. All rights reserved.
    This code is licensed under the Microsoft Public License.
    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

*********************************************************/
using System;
using System.Windows;
using OData.Silverlight;
using System.Data.Services.Client;

namespace SL_OData_Explorer.Utilities
{
    public class QueryUtility
    {
        public delegate void OnQueryBeginDelegate(IAsyncResult CurrentQuery);
        public delegate void OnQueryCompletedDelegate(QueryOperationResponse Response, Exception Error);


        public event OnQueryCompletedDelegate OnQueryCompleted;
        public event OnQueryBeginDelegate OnQueryBegin;


        private IAsyncResult CurrentQueryResult;
        private ODataServiceContext serviceContext;
        public ODataServiceContext ServiceContext
        {
            get
            {
                if (serviceContext == null)
                {
                    throw new InvalidOperationException("The ServiceContext is not initialized yet");
                }
                return serviceContext;
            }
            set
            {
                serviceContext = value;
            }
        }



        public void DoGET(DataServiceQuery<ODataEntity> entityQuery)
        {
            CurrentQueryResult = entityQuery.BeginExecute(QueryCallback, entityQuery);
        }
        private void QueryCallback(IAsyncResult asyncResult)
        {
            QueryOperationResponse response = null;
            DataServiceQuery<ODataEntity> entityQuery = asyncResult.AsyncState as DataServiceQuery<ODataEntity>;
            Exception error = null;
            try
            {
                if (entityQuery == null)
                {
                    response = ServiceContext.EndExecute<ODataEntity>(asyncResult) as QueryOperationResponse;
                }
                else
                {
                    response = entityQuery.EndExecute(asyncResult) as QueryOperationResponse;
                }
            }
            catch (Exception queryException)
            {
                error = queryException;
            }
            finally
            {
                CurrentQueryResult = null;
                if (this.OnQueryCompleted != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(
                        () =>
                        {
                            OnQueryCompleted(response, error);
                        }
                        );
                }
            }
        }
        public void CancelRunningQuery(IAsyncResult asyncResult)
        {
            ServiceContext.CancelRequest(asyncResult);
            CurrentQueryResult = null;
        }
        public void DoGET(EntitySet entitySet, Uri requestUri)
        {

            EntityType entityType = App.MDViewModel.CurrentModel.GetEntityType(entitySet);
            ServiceContext.currentEntityType = entityType;
            CurrentQueryResult = ServiceContext.BeginExecute<ODataEntity>(requestUri, QueryCallback, null);
            if (this.OnQueryBegin != null)
            {
                this.OnQueryBegin(CurrentQueryResult);
            }
        }
        public void DoGET(EntitySet entitySet)
        {
            ServiceContext = new ODataServiceContext(new Uri(App.MDViewModel.CurrentModel.DataServiceUri, UriKind.RelativeOrAbsolute));
            Uri entitySetRequestUri = App.MDViewModel.CurrentModel.ServiceDocument.EntitySetUris[entitySet.SetName];
            this.DoGET(entitySet, entitySetRequestUri);
        }

        public void DoGET(string entitySetName, string additionalURISegments)
        {
            if (String.IsNullOrEmpty(additionalURISegments))
            {
            }
        }
    }
}


